package cn.kbyue.txdemo.service.impl;

import cn.kbyue.txdemo.entity.TxDemo;
import cn.kbyue.txdemo.mapper.TxDemoMapper;
import cn.kbyue.txdemo.service.TxDemoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class TxDemoServiceImpl extends ServiceImpl<TxDemoMapper, TxDemo> implements TxDemoService {

    @Resource
    TxDemoMapper mapper;

    @Autowired
    TxDemoServiceImpl service;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean txSimple() {
        TxDemo demo = new TxDemo();
        demo.setId(1);
        demo.setRemark("玄幻爱情");
        int update = mapper.updateById(demo);
        int i = 5 / 0;
        demo.setName("斗罗大陆");
        mapper.updateById(demo);
        return update > 0;
    }

    @Override
    public boolean txReference() {
        // 事务不生效, 异常前语句会更新成功, 不会回滚
        this.txSimple();
        return true;
    }

    @Override
    public boolean txReferenceValid() {
        // 事务生效, 会回滚
        service.txSimple();
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public boolean txPropagationNew() {
        TxDemo demo = new TxDemo();
        demo.setId(1);
        demo.setRemark("玄幻爱情");
        int update = mapper.updateById(demo);
        // 不会回滚, 因为事务隔离级别为 新建事务, 互不影响
        service.txNew();
        int i = 1 / 0;
        return update > 0;
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void txNew() {
        TxDemo demo = new TxDemo();
        demo.setId(2);
        demo.setRemark("悬疑破案");
        mapper.updateById(demo);
        // int i = 1 / 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class, timeout = 6)
    public boolean findInsertData() {
        TxDemo demo = new TxDemo();
        demo.setId(4);
        demo.setName("神印王座");
        demo.setRemark("玄幻爱情");
        mapper.insert(demo);

        TxDemo txDemo = getById(4);
        assert txDemo != null;
        System.out.println(txDemo);
        return true;
    }

    public TxDemo getById(Integer id) {
        return mapper.selectById(id);
    }

}
